package com.study.graph.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;


@Slf4j
public class FileUtil {

    static int rnCount = 0;

    public static String getMD5(File file) {
        String value = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

    public static void byte2file(byte[] bs, String filename) {
        if (!(new File(filename).exists()))
            try {
                new File(filename).createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filename);
            fos.write(bs);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fos)
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    public static byte[] fileToBytes(String filePath) {
        File file = new File(filePath);
        byte[] ret = null;
        try {
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
            byte[] b = new byte[4096];
            int n;
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n);
            }
            in.close();
            out.close();
            ret = out.toByteArray();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }

    public static boolean moveFile(String oldName, String newName) {
        File oldFile = new File(oldName);
        File newFile = new File(newName);
        try {
            if (newFile.getAbsolutePath().contains("load_error") && oldFile.getName().equalsIgnoreCase(newFile.getName())) {
                newFile = new File(newName + "." + System.currentTimeMillis());
            }
//			long oldL = oldFile.length();
            //	rnCount++;
            //	System.out.println("rnCount:"+rnCount);
            if (oldFile.renameTo(newFile)) {
                log.info("remove file {} to {} ok", oldFile.getAbsolutePath(), newFile.getAbsolutePath());

            } else {
                log.info("remove file {} to {} err", oldFile.getAbsolutePath(), newFile.getAbsolutePath());
                FileUtils.moveFile(oldFile, newFile);
            }


            //Thread.sleep(50);
        } catch (Exception e) {
            log.error("err file move {} to {}", oldFile.getAbsolutePath(), newFile.getAbsolutePath());
            if (oldFile.delete()) {
                log.info("remove err file {} ok", oldFile.getAbsolutePath());
            } else {
                log.info("remove err file {} err", oldFile.getAbsolutePath());
            }
            return false;
        }
        return true;
    }


    /**
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String[] getFileList(String filePath) {
        File file = new File(filePath);
        //if (!file.exists()){
        //	throw new IOException("�ļ�δ�ҵ���" + filePath);
        //}
        return file.list();
    }

    public static void createDir(String filePath) {
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdir();
        }
    }

    public static void deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    files[i].delete();
                }
            }

            if (!(file.delete())) {
                log.error("delete file {} error", file.getAbsolutePath());
            } else {
                log.error("delete file {} ok", file.getAbsolutePath());
            }

        }
    }


    /**
     * @param fileName
     * @param destDir
     */
    @SuppressWarnings("resource")
    public static String unZipFile(String fileName, String destDir) throws IOException {
        String bcpFile = null;
        int len = 0;
        byte[] b = new byte[1024 * 2];
        File file = new File(fileName);
        ZipFile zipFile = new ZipFile(file);
        if (fileName.endsWith(".zip")) {
            ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
            ZipEntry entry = null;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.getName().endsWith(".bcp")) {
                    bcpFile = entry.getName();
                }

                String destFile = null;
                if (destDir.endsWith(File.separator)) {
                    destFile = destDir + entry.getName();
                } else {
                    destFile = destDir + File.separator + entry.getName();
                }
                OutputStream os = new FileOutputStream(destFile);
                InputStream is = zipFile.getInputStream(entry);
                while ((len = is.read(b)) != -1) {
                    os.write(b, 0, len);
                }
                is.close();
                os.close();
            }
        }

        return bcpFile;
    }

    public static void main(String[] args) {
        try {
            unZipFile("D:\\116_LOG_0.370000_4DD24EAE_05070.zip", "D:\\data");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void copyFile(String oldFile, String newFile) {

        File oldfile = new File(oldFile);
        File newfile = new File(newFile);
        if (oldfile.exists()) {
            try {
                log.info("copy file {} to {} start", oldfile.getAbsolutePath(), newfile.getAbsolutePath());
                FileUtils.copyFile(oldfile, newfile);
                log.info("copy file {} to {} ok", oldfile.getAbsolutePath(), newfile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
                log.error("copy file {} to {} err", oldfile.getAbsolutePath(), newfile.getAbsolutePath());
            }
        }
		/*
		FileInputStream in = null;
		FileOutputStream out = null;
		try{
			in = new FileInputStream(oldfile);
			out = new FileOutputStream(newfile);
			byte[] buff = new byte[1024*1024];
			int n=0;
			while((n=in.read(buff))!=-1)
			{
				out.write(buff, 0, n);
			}
			log.info("copy file {} to {} ok",oldfile.getAbsolutePath(),newfile.getAbsolutePath());
		}catch(Exception e){
			e.printStackTrace();
			log.error("copy file {} to {} err",oldfile.getAbsolutePath(),newfile.getAbsolutePath());
			
		}finally{
			try {
				in.close();
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
				
		}
		*/

    }
}
		

